MY_CFLAGS=-Og -g -DDEBUG
ifneq ($(KERNELRELEASE),)
	obj-m := adv_scull.o sleepy.o scull_pipe.o sculluid.o scullpriv.o
	adv_scull-objs := scull.o scull_sysfs.o
	sculluid-objs := scull_uid.o scull_common.o
	scullpriv-objs := scull_priv.o scull_common.o
	ccflags-y += $(MY_CFLAGS)
else
	#KERNELDIR ?= /lib/modules/$(shell uname -r)/build
	KERNELDIR ?= /home/sam/sandbox/linux
	PWD := $(shell pwd)
default:
	$(MAKE) -C $(KERNELDIR) M=$(PWD) modules EXTRA_CFLAGS="$(MY_CFLAGS)"
endif

scull.o: scull.c log.h scull.h ioctl_cmds.h
scull_sysfs.o: scull_sysfs.c log.h scull.h ioctl_cmds.h
scull_common.o: scull_common.c scull_common.h log.h
scull_uid.o: scull_uid.c scull_common.h log.h
scull_priv.o: scull_priv.c scull_common.h log.h
demo.o: demo.c ioctl_cmds.h
	$(CC) -c ${MY_CFLAGS} -I${KERNELDIR}/include -I${PWD} -o $@ $<

demo: demo.o
	$(CC) -static -o $@ $^

sleepy.o: sleepy.c log.h
scull_pipe.o: scull_pipe.c log.h

nbtest.o: nbtest.c log.h
	$(CC) -c ${MY_CFLAGS} -I${PWD} -o $@ $<
nbtest: nbtest.o
	$(CC) -static -o $@ $^

polltest.o: polltest.c log.h
	$(CC) -c ${MY_CFLAGS} -I${PWD} -o $@ $<
polltest: polltest.o
	$(CC) -static -o $@ $^

asynctest.o: asynctest.c log.h
	$(CC) -c ${MY_CFLAGS} -I${PWD} -o $@ $<
asynctest: asynctest.o
	$(CC) -static -o $@ $^

run: default demo nbtest polltest asynctest
	qemu-system-x86_64 -enable-kvm -cpu host -smp 4 \
	-m 256M \
	-nographic \
	-kernel ../../linux/arch/x86_64/boot/bzImage \
	-initrd ../initramfs.tgz \
	-fsdev local,id=ldd,path=$(PWD),security_model=mapped,multidevs=remap \
	-device virtio-9p-pci,fsdev=ldd,mount_tag=ldd \
	-append "nokaslr console=ttyS0 vm_inst=1 kgdbwait kgdboc=ttyS1,115200"

# After running, you can mount the fsdev
# mkdir -p /lib/modules/`uname -r`
# mount -t 9p -o trans=virtio ldd /lib/modules/`uname -r`

debug: default demo nbtest polltest asynctest
	qemu-system-x86_64 -enable-kvm -cpu host -smp 1 \
	-m 256M \
	-nographic \
	-kernel ../../linux/arch/x86_64/boot/bzImage \
	-initrd ../initramfs.tgz \
	-fsdev local,id=ldd,path=$(PWD),security_model=mapped,multidevs=remap \
	-device virtio-9p-pci,fsdev=ldd,mount_tag=ldd \
	-append "nokaslr console=ttyS0 vm_inst=1" \
	-s -S

clean:
	$(MAKE) -C $(KERNELDIR) M=$(PWD) modules clean
	rm -f demo nbtest polltest asynctest *.o

.PHONY: default run debug clean
#	-chardev socket,id=gdb,port=1234,server,nowait,host=0.0.0.0 \
#	-device pci-serial,chardev=gdb \
#	-append "nokaslr console=ttyS0 vm_inst=1 kgdbwait kgdboc=ttyS1,115200"
